import os
import scipy.io
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

folder_path = 'E:\\gitee\\my_class_py\\text_tea\\Tea_Multi_Fluorescence_Spectra'
data = []
labels = []
for root, dirs, files in os.walk(folder_path):
    for dir in dirs:
        # 获取文件夹(茶叶种类)名字
        label = dir
        # 遍历文件夹中的所有文件
        for file in os.listdir(os.path.join(root, dir)):
            # 检查文件是否为mat文件
            if file.endswith('.mat'):
                # 组合文件的完整路径
                file_path = os.path.join(root, dir, file)
                # 使用scipy库的loadmat函数加载mat文件内容
                # 只读取文件内容，不读取文件属性
                mat_data = scipy.io.loadmat(file_path)['spectra']
                # 将数据添加到列表中
                # flatten将多维数组压成一维数组
                data.append(mat_data.flatten())
                labels.append(label)

# 将数据和标签转换为numpy数组
data = np.array(data)
labels = np.array(labels)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42)

# 建立SVC模型
model = SVC()

# 训练模型
model.fit(X_train, y_train)

#导入输出相关的库，生成混淆矩阵
#训练样本的混淆矩阵
cm_train = confusion_matrix(y_train,model.predict(X_train))
print(f"Training Set accuracy = {accuracy_score(y_train,model.predict(X_train)):.2f}")
#训练样本的accuracy
print(cm_train)
cm_test = confusion_matrix(y_test,model.predict(X_test))
#测试样本的混淆矩阵
print(f"Test Set accuracy = {accuracy_score(y_test,model.predict(X_test)):.2f}")
#测试样本的accuracy
print(cm_test)

